﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Security.Principal;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using System.IO.IsolatedStorage;

namespace DomusDotNet.Sbm.Client.SL4.Services
{

    [Export(typeof(ISecurityContext))]
    public class DefaultSecurityContext : ISecurityContext, IHandle<LoggedInEvent>, IHandle<LoggedOutEvent>{


        readonly string KEY= typeof(DefaultSecurityContext).FullName + "/CurrentPrincipal";

        [ImportingConstructor]
        public DefaultSecurityContext(IEventAggregator eventAggregator) {
            eventAggregator.Subscribe(this);


            string userName = null;
            IsolatedStorageSettings.ApplicationSettings.TryGetValue(KEY, out userName);
            CurrentUser = userName == null ? DefaultPrincipal.Null : new DefaultPrincipal(userName, Guid.Empty);
        }


        IPrincipal currentUser;
        public IPrincipal CurrentUser {
            get { return currentUser; }
            private set { 
                currentUser = value;
                IsolatedStorageSettings.ApplicationSettings[KEY] = value.Identity.IsAuthenticated ? value.Identity.Name : null;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }


        void IHandle<LoggedOutEvent>.Handle(LoggedOutEvent message)
        {
            CurrentUser = DefaultPrincipal.Null;
        }

        void IHandle<LoggedInEvent>.Handle(LoggedInEvent message)
        {
            CurrentUser = message.Principal;
        }
    }


    public class LoggedInEvent
    {
        public IPrincipal Principal { get; set; }
    }

    public class LoggedOutEvent
    {

    }


    public interface IIdentityWithToken: IIdentity {
        Guid LoginToken { get; }
    }

    
    public class DefaultPrincipal : IPrincipal, IIdentityWithToken
    {
        public static readonly IPrincipal Null = new DefaultPrincipal();

        private DefaultPrincipal() {
            IsAuthenticated = false;
        }
        public DefaultPrincipal(string name, Guid token) {
            Name = name;
            LoginToken = token;
            IsAuthenticated = true; 
        }
        
        public IIdentity Identity { get { return this; } }
        public bool IsInRole(string role)
        {
            return true;
        }


        public string AuthenticationType
        {
            get { return null; }
        }

        public bool IsAuthenticated { get; private set; }
        public string Name { get; private set; }
        public Guid LoginToken { get; private set; }

    }

}
